package com.android.manghe.box.fragment;

import static com.pay.paytypelibrary.base.PayUtil.PAY_CODE;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

import com.android.base.frame.extend.IRefresh;
import com.android.base.frame.title.ETitleType;
import com.android.base.frame.view.MVPFragment;
import com.android.base.tools.ToastUtil;
import com.android.manghe.R;
import com.android.manghe.box.activity.UnpackingFiveActivity;
import com.android.manghe.box.activity.UnpackingRealActivity;
import com.android.manghe.box.model.BoxModel;
import com.android.manghe.box.model.BoxPrizeModel;
import com.android.manghe.box.model.MessageEvent;
import com.android.manghe.box.model.OpenBoxWayModel;
import com.android.manghe.box.model.PayWayModel;
import com.android.manghe.box.presenter.POpenBox;
import com.android.manghe.cache.UserHolder;
import com.android.manghe.common.model.BuyMemberShangMengZhiFuRes;
import com.android.manghe.common.model.PaymentTypeRes;
import com.android.manghe.common.webview.ERefreshWebType;
import com.android.manghe.common.webview.SimpleWebViewActivity;
import com.android.manghe.common.webview.WebViewActivity;
import com.android.manghe.common.webview.WebViewParameter;
import com.android.manghe.config.Config;
import com.android.manghe.config.events.RefreshMemberInfoEvent;
import com.android.manghe.market.model.BoxCheckOrderModel;
import com.android.manghe.market.model.BoxSubmitModel;
import com.android.manghe.market.view.ConfirmPayResultDialog;
import com.android.manghe.mine.model.SandPayH5Model;
import com.android.manghe.mine.model.SandPayModel;
import com.android.manghe.quickpay.activity.QuickPayDetailActivity;
import com.android.manghe.utils.VoicePlayer;
import com.android.manghe.view.OpenBoxLayout;
import com.android.manghe.view.popWindow.OrderSurePopWindow;
import com.android.manghe.view.popWindow.ShowBoxOpenPopWindow;
import com.eightbitlab.rxbus.Bus;
import com.pay.paytypelibrary.base.OrderInfo;
import com.pay.paytypelibrary.base.PayUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.unionpay.UPPayAssistEx;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * author : liuwen
 * e-mail : liuwen370494581@163.com
 * time   : 2021/10/20 17:21
 * desc   : 开盒页面
 */
public class OpenBoxFragment extends MVPFragment<POpenBox> implements IRefresh {

    public static final int UNION_CODE = 10;
    //杉德对接需要的参数
    private OpenBoxLayout mOpenBoxLayout;
    private int position = 2;

    //支付所需要的参数
    private int mNum = 0;
    private BoxSubmitModel.DataBean mBoxSubmitModel;
    public static final int PayCodeFormFragment = 108, PayCodeFormActivity = 109;
    private View mPopWindowView;


    @Override
    protected void initData(@Nullable Bundle savedInstanceState, View parent) {
        mOpenBoxLayout = parent.findViewById(R.id.id_open_box_view);
        mOpenBoxLayout.setActivity(getActivity());
        getDate();
        mOpenBoxLayout.setListener(new OpenBoxLayout.IOpenBoxLayoutListener() {
            @Override
            public void onClick(View view) {
                mPopWindowView = view;
                ShowBoxOpenPopWindow popWindow = new ShowBoxOpenPopWindow(getActivity(), mOpenBoxLayout.getCurrentBox());
                popWindow.showPopWindow(view);
                popWindow.setListener(new ShowBoxOpenPopWindow.IShowBoxOpenListener() {
                    @Override
                    public void onClick(OpenBoxWayModel model) {
                        getP().getBoxCheckOrder(mOpenBoxLayout.getCurrentBox().id, model.getNum(), view);
                    }
                });


            }
        });
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        VoicePlayer.getInstance().init(mContext);
    }

    @Override
    protected ETitleType showToolBarType() {
        return ETitleType.NO_TITLE;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_open_box;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("MainActivity", "onDestroy");
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (mOpenBoxLayout != null) {
            mOpenBoxLayout.stopMusic();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEventType() == Config.EVENT_BUS_OPEN_MUSIC) {
            position = (int) event.getObject();
            if (mOpenBoxLayout != null) {
                mOpenBoxLayout.startMusic();
            }
        } else if (event.getEventType() == Config.EVENT_BUS_CLOSE_MUSIC) {
            position = (int) event.getObject();
            if (mOpenBoxLayout != null) {
                mOpenBoxLayout.stopMusic();
            }
        } else if (event.getEventType() == Config.EVENT_BUS_SHOW_ORDER) {
            if (event.getObjectB().equals(PayCodeFormFragment)) {
                if (mPopWindowView != null) {
                    showLoadingDialog();
                    getP().getBoxCheckOrder(mOpenBoxLayout.getCurrentBox().id, mNum, mPopWindowView);
                }
            }

        } else if (event.getEventType() == Config.EVENT_BUS_OPEN_SUCCESS) {
            if (mOpenBoxLayout != null) {
                mOpenBoxLayout.stopBoxGift();
                getP().getBoxPrize();
            }
        } else if (event.getEventType() == Config.EVENT_BUS_SAD_PAY_RESULT_UPAY) {
            int requestCode = (int) event.getObject();
            int resultCode = (int) event.getObjectB();
            Intent data = (Intent) event.getObjectC();
            if (requestCode == PAY_CODE) {
                OrderInfo orderInfo = (OrderInfo) data.getSerializableExtra("orderInfo");
                if (orderInfo != null) {
                    if (!TextUtils.isEmpty(orderInfo.getTradeNo())) {
                        startUnionpay(mContext, orderInfo.getTradeNo());
                        Bus.INSTANCE.send(new RefreshMemberInfoEvent());
                        return;
                    }
                }
            }

            if (requestCode == UNION_CODE) {
                Bundle bundle = data.getExtras();
                if (null == bundle) {
                    return;
                }
                /*
                 * 支付控件返回字符串:
                 * success、fail、cancel 分别代表支付成功，支付失败，支付取消
                 */
                getP().setOut_trade_no(null);
                String result = bundle.getString("pay_result");
                if (result != null) {
                    if (result.equalsIgnoreCase("success")) {
                        paySuccess();
                    } else if (result.equalsIgnoreCase("fail")) {
                        payFail();
                    } else if (result.equalsIgnoreCase("cancel")) {
                        ToastUtil.showLong(mContext, "您已取消支付");
                    }
                }
            }
        } else if (event.getEventType() == Config.EVENT_BUS_SAD_PAY_RESULT_ALPAY) {
            String payCode = (String) event.getObject();
            if (payCode.equals("2")) {
                paySuccess();
            } else {
                payFail();
            }
        }
    }

    private void getDate() {
        getP().getBoxTab();
        getP().getBoxPrize();
    }

    public void updateTab(List<BoxModel.DataBean> list) {
        if (mOpenBoxLayout != null) {
            mOpenBoxLayout.updateTab(list);
        }
    }

    public void updateBoxPrize(List<BoxPrizeModel.DataBean.ListBean> list) {
        if (mOpenBoxLayout != null) {
            mOpenBoxLayout.updatePrize(list);
        }
    }


    @Override
    public void onStop() {
        super.onStop();
        Log.e("MainActivity", "onStop");
        if (mOpenBoxLayout != null) {
            mOpenBoxLayout.stopMusic_2();
        }
    }

    @Override
    public SmartRefreshLayout getRefreshView() {
        return mView.findViewById(R.id.id_refreshLayout);
    }

    @Override
    public void onRefresh() {
        getDate();
    }

    @Override
    public void onLoad() {
    }

    public void setCanLoadMore(Boolean canLoadMore) {
        getRefreshView().setEnableLoadMore(canLoadMore);
    }


    /**
     * 更新订单结果
     *
     * @param dateBean
     * @param v
     */
    public void updateCheckOrder(BoxCheckOrderModel.DataBean dateBean, View v) {
        getP().getPaymentType(dateBean, v);
    }


    private List<PaymentTypeRes.DataBean.PaymentBean> paymentList = new ArrayList<>();

    /**
     * 更新支付方式
     *
     * @param payment
     */
    public void updatePayments(List<PaymentTypeRes.DataBean.PaymentBean> payment,
                               BoxCheckOrderModel.DataBean dateBean, View v) {
        this.paymentList = payment;
        OrderSurePopWindow popWindow = new OrderSurePopWindow(getActivity(),
                mOpenBoxLayout.getCurrentBox(), dateBean, paymentList);
        popWindow.showPopWindow(v);
        popWindow.setListener(new OrderSurePopWindow.IOrderSureListener() {
            @Override
            public void pay(BoxCheckOrderModel.DataBean model, PaymentTypeRes.DataBean.PaymentBean paymentBean, int use_score) {
                getP().getBoxSubmitOrder(model.manghe_cat_id + "", model.buy_num, paymentBean.pay_id, paymentBean.pay_code,use_score);
            }

        });

    }

    /**
     * 提交订单
     *
     * @param dataBean
     * @param pay_id
     * @param payCode
     * @param num
     */
    public void updateSubmitModel(BoxSubmitModel.DataBean dataBean, String pay_id, String payCode, int num) {
        this.mNum = num;
        this.mBoxSubmitModel = dataBean;
        if (dataBean.need_pay) {
            //余额不够,直接选择支付
            getP().getOrderMsg(dataBean.order_id + "", pay_id, payCode);
        } else {
            //直接跳转到开奖页面
            paySuccess();

        }
    }

    public void showCheckTip() {
        ToastUtil.showLong(mContext, "获取订单失败,请重试");
    }

    public void showSubmitTip() {
        ToastUtil.showLong(mContext, "支付失败,没有抵扣您的余额和赠送币,请重试");
    }


    public void openQuickPay(BuyMemberShangMengZhiFuRes.DataBean buyMemberShangMengZhiFuData) {
        mOpenBoxLayout.stopMusic_2();
        Intent intent = new Intent(mContext, QuickPayDetailActivity.class);
        intent.putExtra("buyMemberShangMengZhiFuData", buyMemberShangMengZhiFuData);
        startActivityForResult(intent, 2000);
    }

    public void payFail() {
        ToastUtil.showShort(mContext, "未完成支付");
    }

    public void paySuccess() {
        if (mBoxSubmitModel != null) {
            if (mNum == 1) {
                Intent intent = new Intent(mContext, UnpackingRealActivity.class);
                intent.putExtra("BoxListModel", mOpenBoxLayout.getCurrentBox());
                intent.putExtra("orderId", mBoxSubmitModel.order_id);
                intent.putExtra("PayPageWay", PayCodeFormFragment);
                startActivity(intent);
                mOpenBoxLayout.stopMusic_2();
            } else {
                //其他就是跳转到开五个箱子的
                Intent intent = new Intent(mContext, UnpackingFiveActivity.class);
                intent.putExtra("BoxListModel", mOpenBoxLayout.getCurrentBox());
                intent.putExtra("orderId", mBoxSubmitModel.order_id);
                intent.putExtra("PayPageWay", PayCodeFormFragment);
                intent.putExtra("PayCount", mNum);
                startActivity(intent);
                mOpenBoxLayout.stopMusic_2();
            }
        }
    }

    public void toPayByH5(String url) {
        Intent intent = new Intent(mContext, SimpleWebViewActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", "支付");
        startActivity(intent);
    }

    public void toPayByBrowser(String url, String orderId) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
        //弹出让用户确定是否支付成功的弹出框
        if (orderId != null) {
            ConfirmPayResultDialog dialog = new ConfirmPayResultDialog(mContext, orderId, new ConfirmPayResultDialog.CallBack() {
                @Override
                public void callBack(String orderId) {
                    Bus.INSTANCE.send(new RefreshMemberInfoEvent());
                }
            });
            dialog.show();
        }
    }

    //===============================================================对接珊德宝支付======================================
    public void cashierPay(SandPayModel.Data sandPayModel) {
        JSONObject orderJson = new JSONObject();
        try {
            getP().setOut_trade_no(sandPayModel.order.outTradeNo);
            orderJson.put("version", sandPayModel.paycode.version);
            orderJson.put("sign_type", sandPayModel.paycode.signType);
            orderJson.put("mer_no", sandPayModel.paycode.merNo); // 商户编号
            orderJson.put("mer_key", sandPayModel.paycode.merKey); // 商户密钥
            orderJson.put("mer_order_no", sandPayModel.paycode.merOrderNo); // 商户订单号
            orderJson.put("create_time", sandPayModel.paycode.createTime); // 订单创建时间
            orderJson.put("expire_time", sandPayModel.paycode.expireTime); // 订单失效时间
            orderJson.put("order_amt", sandPayModel.paycode.orderAmt); // 订单金额
            orderJson.put("notify_url", sandPayModel.paycode.notifyUrl); // 回调地址
            orderJson.put("return_url", sandPayModel.paycode.returnUrl);//"http://www.baidu.com"); // 支付后返回的商户显示页面
            orderJson.put("create_ip", sandPayModel.paycode.createIp); // 客户端的真实IP
            orderJson.put("goods_name", sandPayModel.paycode.goodsName); // 商品名称
            orderJson.put("store_id", sandPayModel.paycode.storeId); // 门店号
            orderJson.put("product_code", sandPayModel.paycode.productCode); // 支付产品编码
            orderJson.put("clear_cycle", sandPayModel.paycode.clearCycle); // 清算模式
            orderJson.put("accsplit_flag", sandPayModel.paycode.accsplitFlag); // 分账标识 NO无分账，YES有分账
            orderJson.put("sign", sandPayModel.paycode.sign);//签名
            orderJson.put("pay_extra", sandPayModel.paycode.payExtra);
            orderJson.put("jump_scheme", "maincash://mainpay"); // 支付宝返回app所配置的域名
            // orderJson.put("limit_pay", ""); //微信传1屏蔽信用卡，支付宝传5屏蔽部分信用卡以及花呗，支付宝传4屏蔽花呗，支付宝传1屏蔽部分信用卡，银联不支持屏蔽   不参与签名
        } catch (Exception e) {
            e.getStackTrace();
        }
        PayUtil.CashierPay(mContext, orderJson.toString());
    }

    public void cashierPayH5(SandPayH5Model.Data sandPayH5model) {
        getP().setOut_trade_no(sandPayH5model.order.outTradeNo);
        WebViewParameter parameters = new WebViewParameter.WebParameterBuilder()
                .setHtmlUrl(sandPayH5model.paycode.body.credential)
                .setShowProgress(true)
                .setCanHistoryGoBackOrForward(true)
                .setReloadable(true)
                .setShowWebPageTitle(false)
                .setReloadType(ERefreshWebType.ClickRefresh)
                .setCustomTitle("快捷支付")
                .build();
        Intent intent = new Intent(mContext, WebViewActivity.class);
        intent.putExtra("parameters", parameters);
        startActivity(intent);

    }

    /**
     * 银联云闪付
     */
    public static void startUnionpay(Context context, String tradeNo) {
        UPPayAssistEx.startPay(context, null, null, tradeNo, "00");
    }

    public void showPayWay(PayWayModel.Data paWayModel) {
        if (paWayModel.payType.equals("7")) {
            //7表示盲盒订单
            if (paWayModel.payWay == null) {
                return;
            }
            if (paWayModel.payWay.equals("0") ||paWayModel.payWay.equals("1")|| paWayModel.payWay.equals("2")) {
                //表示只有支付宝 和杉德支付宝的时候才调用  只有这两个才会离开app
                getP().setOut_trade_no(null);
                if (paWayModel.isPaid.equals("1")) {
                    paySuccess();
                } else {
                    payFail();
                }
            }

        }
    }


    @Override
    public void onResume() {
        super.onResume();
        Log.e("MainActivity", "onResume");
        if (mOpenBoxLayout != null) {
            if (mOpenBoxLayout.ismIsPlay() && position == 2) {
                mOpenBoxLayout.startMusic();
            }
        }
        //只有当订单号不为空并且position为开盒页面的时候才可以去请求订单号
        if (getP().getOut_trade_no() != null && UserHolder.getUserInfo(mContext) != null && position == 2) {
            getP().getPayWay();
        }

    }
}


